#!/usr/bin/env python
# coding: utf8

import os
import sys
import glob
import id3reader


def rename(mp3, dump=False, execute=True):
    r = id3reader.Reader(mp3)
    if dump:
        r.dump()

    dirname = os.path.dirname(mp3)
    mp3name = os.path.basename(mp3)
    
    songer = r.getValue('performer')
    title = r.getValue('title')

    if songer and title:
        name = "{} - {}.mp3".format(songer.encode('utf8'), title.encode('utf8'))
    elif songer:
        name = "{} - {}".format(songer.encode('utf8'), mp3name)
    elif title:
        name = "{}.mp3".format(title.encode('utf8'))
    else:
        print("{} skipped".format(mp3name))
        return

    dstname = os.path.join(dirname, name)
    if mp3 != dstname:
        print("{} -> {}".format(mp3name, name))
        if execute:
            os.rename(mp3, dstname)


def main(mp3dir, dump, execute):
    for mp3 in glob.glob(os.path.join(mp3dir, "*.mp3")):
        rename(mp3, dump, execute)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("""
Usage: {} [options] mp3dir
options:
    -e  execute rename
    -d  dump tag
""".format(sys.argv[0]))

        sys.exit(0)

    dump = False
    execute = False
    mp3dir = sys.argv[-1]
    for opt in sys.argv[:-1]:
       if opt == "-d":
            dump = True
       elif opt == "-e":
            execute = True

    main(mp3dir, dump, execute)


